package com.zh.juc.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @Author: zhanghuan
 * @date: 2022/10/21 18:18
 * @description: create it
 * 对象属性修改原子类
 * - AtomicIntegerFieldUpdater
 * - AtomicLongFieldUpdater
 * - AtomicReferenceFieldUpdater
 */

class BankAccount {
    private String bankName = "CCB";
    // 更新对象属性必须是 public volatile 修饰
    public volatile int money = 0;

    public void add() {
        money++;
    }

    AtomicIntegerFieldUpdater<BankAccount> fieldUpdater = AtomicIntegerFieldUpdater.newUpdater(BankAccount.class, "money");

    public void transMoney(BankAccount account) {
        fieldUpdater.getAndIncrement(account);
    }
}

/**
 * 10个线程，每个线程转帐1000
 * 不实用synchronized，使用AtomicIntegerFieldUpdater
 */
public class AtomicIntegerFieldUpdaterDemo {
    public static void main(String[] args) throws InterruptedException {
        BankAccount bankAccount = new BankAccount();
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    for (int j = 0; j < 1000; j++) {
                        // bankAccount.add();
                        bankAccount.transMoney(bankAccount);

                    }
                } finally {
                    countDownLatch.countDown();
                }

            }, String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + "\t" + bankAccount.money);

    }
}
